﻿using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CallCenter.Data;
using CallCenter.Data.BizUtilities;
using System.Configuration;
using System.Data;
using CallCenter.Security;
using CallCenter.Data.Models;
using CallCenter.Data.Misc;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web.Caching;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using CallCenter.Data.Helper;
using System.Collections;

namespace CallCenter.Web.Controllers
{
    public class InvoiceController : BaseController
    {
        private static string _conn;
        DB dbConn;
        // GET: Invoice
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult InvoiceHistory()
        {
            InvoiceVM cmpy = new InvoiceVM();
            return View(cmpy);
        }
        public JsonResult GetInvoice(int id)
        {
            var scratchPads = this.Bridge.InvoiceUtility.GetAllGrid(id);
            return Json(scratchPads, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetAllCompanies()
        {
            var scratchPads = this.Bridge.InvoiceUtility.GetAllCompanies();

            return Json(scratchPads, JsonRequestBehavior.AllowGet);

        }

        public JsonResult GetAllProductsRequest(int id)
        {
            var scratchPads = this.Bridge.ProductRequestUtility.GetAllProductRequests(id);

            return Json(scratchPads, JsonRequestBehavior.AllowGet);

        }
        [HttpPost]
        public JsonResult CreateInvoice(InvoiceVM model)
        {
           
            int userId = this.Bridge.AccountUtility.GetUserIDByUserNames(User.Identity.Name.ToLower());
            model.userId = userId;

            var returnMessage = this.Bridge.InvoiceUtility.InsertToInvoice(model); ;
            if (!returnMessage.Status)
                ModelState.AddModelError("Error", returnMessage.Message);
            else
            {
                if (model.term.ToLower() == "once")
                    SendInvoiceReportBySelectedMail(model.id, model.companyId);
                return Json(new AjaxSuccess { Message = "Success" }, JsonRequestBehavior.AllowGet);
            }
         

            return Json(new AjaxFailure { Errors = ModelState.SerializeErrors }, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult DeleteInvoice(InvoiceVM model)
        {
            //insert items into respective tables
            int id = model.id;
            this.Bridge.InvoiceUtility.Delete(id);
            var returnMessage = "Success";
            return Json(returnMessage, JsonRequestBehavior.AllowGet);

        }

        [HttpPost]
        public JsonResult UpdateInvoice(InvoiceVM model)
        {
            var userId = Convert.ToInt32(this.Session["SessionUserId"]);
            model.userId = userId;
            var result = this.Bridge.InvoiceUtility.UpdateToInvoice(model);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        #region
        [HttpPost]
        public ActionResult generateInvoicePdf(int invoiceId)
        {
            #region getting header items
            string filepath = "";
            string fileName = "";
            string baseUrl = "";

            DataRow dr = this.Bridge.InvoiceUtility.Invoic2PDF(invoiceId);
            if (dr == null)
                return null;
            else
            {
                string billTo = dr["compName"].ToString();
                string term = dr["term"].ToString();
                string product = dr["productName"].ToString();
                string project = dr["projectname"].ToString();
                string desc = dr["description"].ToString();
                DateTime tempDate = DateTime.Parse(dr["invoiceDate"].ToString());
                string date = tempDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                string streetOne = dr["streetOne"].ToString();
                string streetTwo = dr["streetTwo"].ToString();
                string compCity = dr["compCity"].ToString();
                string compState = dr["compState"].ToString();
                string period = dr["period"].ToString();
                #endregion

                #region defining font
                BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                BaseFont tFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1257, false);
                BaseFont valFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1257, false);
                Font timesTitle = new Font(bfTimes, 18, Font.BOLD, BaseColor.BLACK);
                Font times = new Font(bfTimes, 14, Font.BOLD, BaseColor.BLACK);
                Font header = new Font(tFont, 13, Font.NORMAL, BaseColor.BLACK);
                Font valueFont = new Font(valFont, 11, Font.NORMAL, BaseColor.BLACK);
                Font georgia = FontFactory.GetFont("georgia", 12f);
                #endregion



                #region defining pdf path and property
                var pdf = new Document();
                string path = Server.MapPath("../");
                DirectoryInfo di = null;

                /*
                 * Invoice folder directroy will be under company name.
                 * Invoice name will be product request name + invoice Id.
                 * 
                 */

                try
                {

                    if (!Directory.Exists(path + "Invoices\\" + billTo.Trim().Replace(' ', '_')))

                        di = Directory.CreateDirectory(path + "\\Invoices\\" + billTo.Trim().Replace(' ', '_'));

                    filepath = path + "Invoices\\" + billTo.Trim().Replace(' ', '_') + "\\" + product.Trim().Replace(' ', '_') + invoiceId + ".pdf";
                    fileName = "Invoices/" + billTo.Trim().Replace(' ', '_') + "/" + product.Trim().Replace(' ', '_') + invoiceId + ".pdf";
                    if (System.IO.File.Exists(filepath))
                    {
                        System.IO.File.Delete(filepath);
                        //if (Cache["List"] != null)
                        //    Cache["List"] = null;
                    }
                    PdfWriter.GetInstance(pdf, new System.IO.FileStream(filepath, FileMode.Create));
                    pdf.Open();
                    pdf.SetMargins(100, 100, 120, 120);

                    #endregion


                    #region header of invoice
                    PdfPCell headerEmptyRow = new PdfPCell(new Phrase(""));
                    headerEmptyRow.Colspan = 4;
                    headerEmptyRow.BorderWidth = 0;
                    PdfPTable headerTable = new PdfPTable(3); //create table with 3 column
                    headerTable.WidthPercentage = 100f;
                    PdfPCell headerCell = new PdfPCell(new Phrase("INVOICE\n\n", timesTitle));
                    headerCell.Colspan = 3;
                    headerCell.HorizontalAlignment = 1;
                    headerCell.BorderWidth = 0;
                    headerTable.AddCell(headerCell);



                    PdfPCell coAdCl = new PdfPCell(new Phrase("Resource Navigation, Inc.\n26 Fox Road \nWaltham, MA 02451"));
                    coAdCl.BorderWidth = 0;
                    headerTable.AddCell(coAdCl);


                    PdfPCell emptyCell = new PdfPCell(new Phrase(" "));
                    emptyCell.BorderWidth = 0;
                    headerTable.AddCell(emptyCell);


                    PdfPCell dateCell = new PdfPCell(new Phrase("Date: " + date + "\nInvoice No.: " + invoiceId.ToString()));
                    dateCell.HorizontalAlignment = 2;
                    dateCell.BorderWidth = 0;
                    headerTable.AddCell(dateCell);


                    headerTable.AddCell(headerEmptyRow);
                    headerTable.AddCell(headerEmptyRow);
                    headerTable.AddCell(headerEmptyRow);
                    headerTable.AddCell(headerEmptyRow);



                    PdfPCell billToCell = new PdfPCell(new Phrase("Bill To: \n", times));
                    billToCell.BorderWidth = 0;
                    headerTable.AddCell(billToCell);
                    headerTable.AddCell(emptyCell);
                    headerTable.AddCell(emptyCell);

                    DateTime TempdueDate = DateTime.Now.Date;
                    string dueDate = TempdueDate.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));

                    PdfPCell dueOnCell = new PdfPCell(new Phrase("Due within " + period + " days of\n" + dueDate));
                    dueOnCell.HorizontalAlignment = 2;
                    dueOnCell.BorderWidth = 0;


                    PdfPCell billToName = new PdfPCell(new Phrase(billTo + "\n" + streetOne + "\n" + streetTwo + "\n" + compCity + " " + compState + " \n"));
                    billToName.BorderWidth = 0;
                    headerTable.AddCell(billToName);
                    headerTable.AddCell(emptyCell);
                    headerTable.AddCell(dueOnCell);
                    pdf.Add(headerTable);
                    #endregion

                    #region invoice Table

                    PdfPCell InvoieEmptyRow = new PdfPCell(new Phrase("")); // empty row.
                    InvoieEmptyRow.Colspan = 5;
                    InvoieEmptyRow.BorderWidth = 0;

                    PdfPTable invoiceTable = new PdfPTable(5);
                    invoiceTable.WidthPercentage = 100f;
                    invoiceTable.TotalHeight.Equals(100f);
                    invoiceTable.AddCell(InvoieEmptyRow);
                    invoiceTable.AddCell(InvoieEmptyRow);
                    invoiceTable.AddCell(InvoieEmptyRow);
                    PdfPCell cell = new PdfPCell(new Phrase("Invoice Details", times)); //title spanning 4 columns
                    cell.BorderWidth = 0;
                    cell.HasMinimumHeight();
                    //cell.Height = 60f;
                    cell.MinimumHeight = 60f;
                    //cell.BackgroundColor = new BaseColor(136, 136, 136);
                    cell.Colspan = 5; //5 is how many no. of columns it covers, 
                    cell.HorizontalAlignment = 1; // 0=left, 1=center, 2=right
                    cell.VerticalAlignment = 1;
                    //PdfPCell podesc = new PdfPCell(new Phrase("P.O. No.", times)); //title spanning 4 columns
                    //podesc.Colspan = 2;
                    //invoiceTable.AddCell(podesc);//col 2 row 1

                    //PdfPCell termdesc = new PdfPCell(new Phrase("Terms", times)); //title spanning 4 columns
                    //termdesc.Colspan = 2;
                    //invoiceTable.AddCell(termdesc);//col 2 row 1

                    //PdfPCell projectdesc = new PdfPCell(new Phrase("Project", times)); //title spanning 4 columns
                    //projectdesc.Colspan = 2;
                    //invoiceTable.AddCell(projectdesc);//col 2 row 1

                    invoiceTable.AddCell(InvoieEmptyRow);
                    invoiceTable.AddCell(InvoieEmptyRow);
                    invoiceTable.AddCell(InvoieEmptyRow);
                    invoiceTable.AddCell(cell); //adding title to pdf line.
                    invoiceTable.AddCell(InvoieEmptyRow);
                    //invoiceTable.AddCell("Sn. No."); //col 1 row 1
                    //invoiceTable.AddCell(cell); //adding title to pdf line.
                    invoiceTable.AddCell(InvoieEmptyRow);

                    //**************************Po No
                    PdfPCell Empty = new PdfPCell(new Phrase("")); //title spanning 4 columns
                                                                   //  Empty.Colspan = 2;
                    Empty.BorderWidth = 0;

                    invoiceTable.AddCell(Empty);//col 2 row 1

                    PdfPCell podesc = new PdfPCell(new Phrase("P.O. No.", times)); //title spanning 4 columns
                                                                                   // podesc.Colspan = 2;
                    invoiceTable.AddCell(podesc);//col 2 row 1


                    PdfPCell termdesc = new PdfPCell(new Phrase("Terms", times)); //title spanning 4 columns
                                                                                  //  termdesc.Colspan = 2;
                    invoiceTable.AddCell(termdesc);//col 2 row 1

                    PdfPCell projectdesc = new PdfPCell(new Phrase("Project", times)); //title spanning 4 columns
                    projectdesc.Colspan = 2;
                    invoiceTable.AddCell(projectdesc);//col 2 row 1
                    DataTable dtbl = this.Bridge.InvoiceItemsUtility.getPdfItems(invoiceId);
                    if (dtbl.Rows.Count > 0)
                    {
                        PdfPCell _EmptyData = new PdfPCell(new Phrase("")); //title spanning 4 columns
                                                                            //_EmptyData.Colspan = 2;
                        _EmptyData.BorderWidth = 0;

                        invoiceTable.AddCell(_EmptyData);//col 2 row 1

                        PdfPCell _EmptyPO = new PdfPCell(new Phrase("")); //title spanning 4 columns
                        //_EmptyData.Colspan = 2;
                        //_EmptyPO.BorderWidth = 0;

                        invoiceTable.AddCell(_EmptyPO);//col 2 row 1

                        var _row = dtbl.Rows[0];
                        string terms = _row["term"].ToString();
                        string projectname = _row["projectname"].ToString();
                        PdfPCell terrmCell = new PdfPCell(new Phrase(terms));//DynamicValues for Item Goes here
                        terrmCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                                          //    terrmCell.Colspan = 2;
                        invoiceTable.AddCell(terrmCell);

                        PdfPCell projectCell = new PdfPCell(new Phrase(projectname));//DynamicValues for Item Goes here
                        projectCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                        projectCell.Colspan = 2;
                        invoiceTable.AddCell(projectCell);
                    }



                    //**************************Po No


                    PdfPCell cellDesc = new PdfPCell(new Phrase("Item Description", times)); //title spanning 4 columns
                    //cellDesc.Colspan = 2;
                    invoiceTable.AddCell(cellDesc);//col 2 row 1

                    PdfPCell cellQty = new PdfPCell(new Phrase("Quantity", times)); //title spanning 4 columns
                    invoiceTable.AddCell(cellQty); //col 3 row 1

                    PdfPCell cellUnitPrice = new PdfPCell(new Phrase("Unit Price", times)); //title spanning 4 columns
                    invoiceTable.AddCell(cellUnitPrice);

                    PdfPCell cellAmt = new PdfPCell(new Phrase("Amount", times)); //title spanning 4 columns
                    cellAmt.Colspan = 2;
                    invoiceTable.AddCell(cellAmt); // col 4 row 1
                    #endregion

                    #region if items list is null
                    PdfPTable emptyTable = new PdfPTable(5);
                    PdfPCell emptyItem = new PdfPCell(new Phrase("Invoice dosen't contain any items", timesTitle)); //defining cell value if its empty
                    emptyItem.Colspan = 5;
                    emptyItem.HorizontalAlignment = 1;
                    emptyItem.BorderWidth = 0;
                    emptyTable.AddCell(emptyItem);
                    #endregion

                    #region getting data rows for





                    if (dtbl == null)
                        pdf.Add(emptyTable);//defined cell in region (if items list is null)
                    else
                    {
                        int rowCount = dtbl.Rows.Count;
                        double sum = 0;
                        if (rowCount == 0)
                            pdf.Add(emptyTable);//defined cell in region (if items list is null)
                        else
                        {
                            for (int i = 0; i < rowCount; i++)
                            {
                                SqlDataAdapter da = new SqlDataAdapter();
                                DataRow drw = dtbl.NewRow();
                                var row = dtbl.Rows[i];
                                //string terms = row["term"].ToString();
                                //string projectname = row["projectname"].ToString();

                                string item = row["itemDescription"].ToString();
                                string quantity = row["quantity"].ToString();
                                //amount int to currency
                                string amountTemp = row["amount"].ToString(); // getting amount from database
                                double amount = Convert.ToDouble(amountTemp); // converting to double data type 
                                string amountMoney = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US")); //taking double amount and giving format of currency

                                //unit price same as amount above
                                string unitPriceTemp = row["unitPrice"].ToString();
                                double unitPdouble = Convert.ToDouble(unitPriceTemp);
                                string unitPrice = unitPdouble.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));

                                /*PdfPCell snCell = new PdfPCell(new Phrase(Convert.ToInt32(i + 1).ToString()));//dynamic serial no.
                                snCell.HorizontalAlignment = 2; // aligment of the text, 2 for right.
                                invoiceTable.AddCell(snCell);
                                 */

                                //**************************Po No

                                //PdfPCell terrmCell = new PdfPCell(new Phrase(terms));//DynamicValues for Item Goes here
                                //terrmCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                //terrmCell.Colspan = 2;
                                //invoiceTable.AddCell(terrmCell);

                                //PdfPCell projectCell = new PdfPCell(new Phrase(projectname));//DynamicValues for Item Goes here
                                //projectCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                //projectCell.Colspan = 2;
                                //invoiceTable.AddCell(projectCell);
                                //**************************Po No

                                PdfPCell itemCell = new PdfPCell(new Phrase(item));//DynamicValues for Item Goes here
                                itemCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                                                 //  itemCell.Colspan = 2;
                                invoiceTable.AddCell(itemCell);

                                PdfPCell qCell = new PdfPCell(new Phrase(quantity));//DynamicValue for quantity goes here
                                qCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                                              //   qCell.Colspan = 2;
                                invoiceTable.AddCell(qCell);

                                PdfPCell upCell = new PdfPCell(new Phrase(unitPrice));//DynamicValue for unitPrice goes here
                                upCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                invoiceTable.AddCell(upCell);

                                PdfPCell atCell = new PdfPCell(new Phrase(amountMoney.ToString()));//DynamicValue for amount goes here
                                atCell.Colspan = 2;
                                atCell.HorizontalAlignment = 0;// aligment of the text, 2 for right.
                                invoiceTable.AddCell(atCell);

                                sum += Convert.ToDouble(amount);
                            }
                            #endregion
                            #region bottom of the invoice
                            double sumAmount = Convert.ToDouble(sum);
                            string sumMoney = sum.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));

                            PdfPCell empCell = new PdfPCell(new Phrase(""));
                            empCell.BorderWidth = 0;
                            invoiceTable.AddCell(empCell);
                            invoiceTable.AddCell(empCell);
                            invoiceTable.AddCell(empCell);
                            PdfPCell totCell = new PdfPCell(new Phrase("Total ", times));
                            totCell.HorizontalAlignment = 0;
                            invoiceTable.AddCell(totCell);
                            PdfPCell amtCell = new PdfPCell(new Phrase(sumMoney));
                            amtCell.HorizontalAlignment = 0;
                            invoiceTable.AddCell(amtCell);
                            pdf.Add(invoiceTable);
                        }
                        #endregion
                    }
                }

                catch (Exception ex)
                {

                }
                finally
                {
                    pdf.Close();
                    baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"].ToString();


                }
                return Json(baseUrl + fileName, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion
        public string GetInvoiceContactsViewToSendReport(int invoiceId, int CompanyId)
        {
            _conn = ConfigurationManager.ConnectionStrings["mainConnection"].ToString();
            dbConn = new DB(_conn);
            Hashtable ht = new Hashtable();
            ht.Add("invoiceId", invoiceId);
            ht.Add("CompanyId", CompanyId);
            DataSet HDDList = dbConn.GetDataSetForSP("Sp_GetAllEmployeeByProductIDandCompanyID", ht);
            List<EmployeeMailVM> EmployeeMailVMList = new List<EmployeeMailVM>();

            EmployeeMailVMList.AddRange(HDDList.Tables[0].AsEnumerable().Select(dataRow =>
                new EmployeeMailVM
                {
                    email = dataRow.Field<string>("email"),
                    firstName = dataRow.Field<string>("firstName"),
                    lastName = dataRow.Field<string>("lastName"),
                    Role = "InvoiceEmployee"
                }).ToList());


            ViewBag.InvoiceId = invoiceId;
            ViewBag.CompanyId = CompanyId;
            return RenderRazorViewToString("~/Views/ProductRequestGrid/_EmailPartialView.cshtml", EmployeeMailVMList);
        }


        public string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                         viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                             ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

        public string SendInvoiceReportBySelectedMail(int invoiceId, int CompanyId)
        {
            try
            {
                DataRow dr = this.Bridge.InvoiceUtility.Invoic2PDF(invoiceId);
                string subject = "Invoice  Report";
                string filePath = Server.MapPath("~/Template/InvoiceReportTemplate.html");

                string content = System.IO.File.ReadAllText(filePath);
                DataTable dtblCompany = this.Bridge.CompanyUtility.GetCompanyByID(CompanyId);
                DataTable dtbl = this.Bridge.InvoiceItemsUtility.getPdfItems(invoiceId);
                string TableContent = "";
                if (dtbl.Rows.Count > 0)
                {
                    var _row = dtbl.Rows[0];
                    string _term = _row["term"].ToString();
                    string _project = _row["projectName"].ToString();
                    TableContent += " <div style='text-align: center;width: 100%;font-weight: bolder;'>Invoice Details</div>";
                    TableContent += "<table class='TableDetail' style='width: 95%; float: left; border: 1px solid; margin: 10px; float: left;'>";
                    TableContent += "<tr>";
                    TableContent += "<th>";
                    TableContent += "</th>";
                    TableContent += "<th> P.O.No";
                    TableContent += "</th>";
                    TableContent += "<th>Terms";
                    TableContent += "</th>";
                    TableContent += "<th> Project";
                    TableContent += "</th>";
                    TableContent += "</tr>";
                    TableContent += "<tr>";
                    TableContent += "<td>";
                    TableContent += "</td>";
                    TableContent += "<td> P.O.No";
                    TableContent += "</td>";
                    TableContent += "<td>" + _term;
                    TableContent += "</td>";
                    TableContent += "<td>" + _project;
                    TableContent += "</td>";
                    TableContent += "</tr>";
                    TableContent += "<tr>";
                    TableContent += "<th>Item Description</th>";
                    TableContent += "<th>Quantity</th>";
                    TableContent += "<th>Unit Price</th>";
                    TableContent += "<th>Amount</th>";
                    TableContent += "</tr>";
                    double TotalMoney = 0;
                    for (int i = 0; i < dtbl.Rows.Count; i++)
                    {
                        TableContent += "<tr style='border: 1px solid;>";
                        var row = dtbl.Rows[i];

                        string term = row["term"].ToString();
                        string project = row["projectName"].ToString();
                        string item = row["itemDescription"].ToString();
                        string quantity = row["quantity"].ToString();
                        //amount int to currency
                        string amountTemp = row["amount"].ToString(); // getting amount from database
                        double amount = Convert.ToDouble(amountTemp); // converting to double data type 
                        TotalMoney += amount;
                        //unit price same as amount above
                        string unitPriceTemp = row["unitPrice"].ToString();
                        double unitPdouble = Convert.ToDouble(unitPriceTemp);
                        string unitPrice = unitPdouble.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));

                        //TableContent += "<td'>" + term + "</td>";
                        //TableContent += "<td'>" + project + "</td>";
                        TableContent += "<td'>" + item + "</td>";
                        TableContent += "<td'>" + quantity + "</td>";
                        TableContent += "<td'>" + unitPrice + "</td>";
                        TableContent += "<td'>" + amountTemp + "</td>";
                        TableContent += "</tr>";

                    }
                    TableContent += "<tr style='border: 1px solid;'><td></td><td></td><td>Total</td>";
                    TableContent += "<td style='border: 1px solid;'>" + TotalMoney.ToString("C", CultureInfo.CreateSpecificCulture("en-US")) + "</td>";
                    TableContent += "</table>";
                }
                else
                {
                    TableContent += "No Invoice found";
                }
                if (dtbl.Rows.Count > 0)
                {
                    string terms = dtbl.Rows[0]["term"].ToString();
                    string projectname = dtbl.Rows[0]["projectname"].ToString();
                    content = content.Replace("##TERM##", terms);
                    content = content.Replace("##PROJECT##", projectname);
                }

                content = content.Replace("##TABLECONTENT##", TableContent);
                content = content.Replace("###INVOICEDATE###", DateTime.Now.ToString("dd/mmm/yyyy"));
                content = content.Replace("####INVOICENO###", invoiceId.ToString());
                string BillToContent = "";
                if (dtblCompany.Rows.Count > 0)
                {
                    BillToContent += " <span>" + dtblCompany.Rows[0]["streetOne"].ToString() + "</span> <br />";
                    BillToContent += " <span>" + dtblCompany.Rows[0]["streetTwo"].ToString() + "</span> <br />";
                    BillToContent += " <span>" + dtblCompany.Rows[0]["city"].ToString() + "</span> <br />";
                }

                content = content.Replace("##BILLTOCONTENT##", BillToContent);
                //content = content.Replace("###LeadDeveloper###", dr["leadDeveloperName"].ToString());             
                //content = content.Replace("###Company###", dr["clientCompany"].ToString());
                //content = content.Replace("###ProjectName###", dr["project"].ToString());
                DataTable contacts = this.Bridge.InvoiceItemsUtility.GetContactsByInvoiceId(invoiceId);
                var ContactArray = contacts.AsEnumerable().Select(s => s.Field<string>("email")).Distinct().ToArray();
                string Body = content;
                string[] to = ContactArray;
                string[] cc = { };
                WebMail.SendMail(to, cc, subject, Body, null);
                return "Mail sent Successfully";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }



        public class InvoiceEmployeeMailVM
        {
            public string email { get; set; }
            public string firstName { get; set; }
            public string lastName { get; set; }
            public string Role { get; set; }
        }




    }
}


